﻿using System;
using System.Collections.Generic;
using Mono.Cecil;
using NDasm.Core.UI.Base;

namespace NDasm.Core.UI.Tree
{
    public class AssemblyTreeViewModel : HierarchicalViewModel, IDisposable
    {        
        private const string Scope = "assemblyTree";

        public AssemblyTreeViewModel(ModuleDefinition moduleDefinition) : base(string.Empty)
        {
            children.Add(new AssemblyNodeViewModel(moduleDefinition, Scope) { IsExpanded = true });
            SelectedItemChanged += SelectedItemChangedHandler;
        }

        private HierarchicalViewModel selectedItem;
        public HierarchicalViewModel SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (value == selectedItem)
                    return;
                selectedItem = value;
                NotifyPropertyChanged(() => SelectedItem);
            }
        }

        private void SelectedItemChangedHandler(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.Scope != Scope || !e.IsSelected)
                return;
            SelectedItem = (HierarchicalViewModel)sender;
        }

        public void Dispose()
        {
            SelectedItemChanged -= SelectedItemChangedHandler;
        }

        public void SelectMember(IMemberDefinition member)
        {
            SelectedItem = null;
            TrySelectMember(this, member);            
        }

        private bool TrySelectMember(HierarchicalViewModel model, IMemberDefinition member)
        {
            foreach (HierarchicalViewModel child in model.Children)
            {
                var memberNode = child as MemberNodeViewModel;
                if (memberNode != null && memberNode.IsSameMember(member))
                {
                    SelectedItem = memberNode;
                    SelectedItem.IsSelected = true;
                    SelectedItem.IsExpanded = true;
                    model.IsExpanded = true;
                    return true;
                }
                if (TrySelectMember(child, member))
                {
                    model.IsExpanded = true;
                    return true;
                }
            }
            return false;
        }
    }
}
